<template>
  <div class="contentType" id="contentType">
    <!-- 功能按钮 -->
    <div class="contentType_button">
      <a-button class="addButton" type="primary" :disabled="!btnPerm.includes('creatAble')" @click="addRecord">
        <template #icon>
          <span class="iconfont icon-Add iconadd"></span>
        </template>
        新建
      </a-button>

      <div class="searchContent">
        <a-input v-model:value="name" placeholder="搜索内容类型名称" style="width: 192px">
          <template #suffix>
            <i class="iconfont icon-search" @click="onSearch"></i>
          </template>
        </a-input>
      </div>
    </div>
    <!-- 表格展示部分 -->
    <baseTable :columns="columns.contentTypeColumns" :dataSource="configData.records" :isSelect="true" :scroll="scroll"
      ref="tagBaseTables" :isShowPagination="isShowPagination" :showCheckDelete="showCheckDelete"
      :total="configData.total" @changePage="changePage">
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.ellipsis">
          <table-tool-tip :text="text" :column="column"></table-tool-tip>
        </template>
        <template v-if="column.dataIndex === 'logoUrl'">
          <img :src="record.logoUrl" alt="" class="pic" @click="seeBigPic(record.logoUrl)" />
        </template>

        <template v-if="column.dataIndex === 'oparation'">
          <a class="eidtRecords" :class="{ disable: !btnPerm.includes('editAble') }" @click="eidtRecord(record)">{{
            record.oparation[0] }}</a>
          <a-popconfirm placement="topRight" :disabled="!btnPerm.includes('deleteAble')" @confirm="confirmDelete(record)">
            <template #title>
              <p style="width: 197px">删除此内容类型后，内容处也同时删除</p>
            </template>
            <a :class="{ disable: !btnPerm.includes('deleteAble') }">{{ record.oparation[1] }}</a>
          </a-popconfirm>
        </template>
      </template>
      <template #otherOpration>
        <a-button :style="{ 'margin-left': '8px' }" @click="deleteSelectedAll"
          :disabled="!rowSelection.length">删除</a-button></template>
    </baseTable>
    <!-- 新建内容类型模态框 -->
    <base-modal :width="modAlProps.width" :isVisible="isVisible" :title="modAlProps.title" :buttons="buttons"
      @handleOk="buttonMessage" @handleCancle="isVisible = false" class="tagword_modal" v-if="isVisible">
      <template v-slot:body>
        <a-form name="advanced_search" class="ant-advanced-search-form" autoComplete="off" :model="formState"
          ref="contentTypeFrom">
          <a-form-item :name="['contentType', 'value']" :label="formState.contentType.label"
            :rules="[formState.contentType.rule]">
            <a-input v-model:value="formState.contentType.value" show-count :maxlength="25" allow-clear />
          </a-form-item>
          <a-form-item :name="['contentIcon', 'value']" :label="formState.contentIcon.label"
            :rules="[formState.contentIcon.rule]">
            <upload :fileList="uploadList" @uploadFinished="uploadFinished"
              @upload_remove_Finished="upload_remove_Finished" :maxCount="1" :accept="'png,jpg,jpeg,gif'" :title="'上传图片'"
              :imgSuggest="'建议40*40PX'" :isAutoUpload="true"></upload>
          </a-form-item>
        </a-form>
      </template>
    </base-modal>
    <!-- 列表图片预览 -->
    <base-modal :width="modAlProps.width" :isVisible="previewVisible" title="图片预览" :isCancleBtn="false" :buttons="buttons"
      @handleCancle="previewVisible = false" class="upload_modal">
      <template v-slot:body>
        <img alt="previewImage" :style="styles" :src="recordSrc" />
      </template>
    </base-modal>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, computed, onMounted, nextTick, createVNode } from "vue";
import baseTable from "@/components/table/baseTable.vue";
import tableToolTip from "@/components/table/tableToolTip.vue";
import columns from "@/components/table/tableConfig/columnsName";
import { getTableScroll } from "@/components/table/tableConfig/table";
import baseModal from "@/components/modal/baseModal.vue";
import msgModal from "@/components/modal/modelConfig/MsGModal";
import { Modal, message } from "ant-design-vue";
import upload from "@/components/upload/uploadFile.vue";
import request from "@/api/index";
import { checkContentName } from "./formRuler";
import { scrollType, modeProp } from "@/type.d";
import { routerPerm } from '@/utils/common';
// type
type configDataType = {
  total: number;
  size: number;
  records: any[];
};
interface dataSourceType {
  [propName: string]: any;
}
//data
const btnPerm = ref<any[]>([]);
let scroll: scrollType = reactive({ y: "", isFixed: false }); // 表单滚动设置
const isShowPagination = true; // 是否需要配分页器
const showCheckDelete = true; // 是否需要分页器中的自定义全选和删除
let name = ref<string>("");
//表格数据
let configData = reactive<configDataType>({ total: 0, size: 10, records: [] });
const tagBaseTables = ref<any>(null); // basetable的ref
let rowSelection = ref<(string | number)[]>([]);
const deleteArr = ref<(string | number)[]>([]);
const uploadList = ref<dataSourceType[]>([]);
const recordSrc = ref<string>("");
const styles = ref<string>("");
const previewVisible = ref<boolean>(false);
// 模态框数据
const isAddOrEdit = ref<boolean>(true); //判断是新家、编辑或者批量上传来复用模态框
const isVisible = ref<boolean>(false);
const modAlProps: modeProp = reactive({
  width: "M",
  title: "新建内容类型",
});

const contentTypeFrom = ref<any>("contentTypeFrom");

const formState = reactive<dataSourceType>({
  contentType: {
    value: "",
    rule: {
      required: true,
      validator: checkContentName,
      trigger: ["blur"],
      msg1: "内容类型名称不可为空！",
      msg2: "内容类型名称已存在！",
      api: "fetchContentTypeUniqueName",
      id: "",
      params: {},
    },
    label: "内容类型名称",
  },
  contentIcon: {
    value: "",
    rule: {
      required: false,
      message: "",
    },
    label: "内容类型图标",
  },
  logoId: "",
  id: "",
});
const buttons = ref<dataSourceType[]>([]); //模态框button按钮个数和文案修改
let datas = reactive<dataSourceType>({});
// 当前页和数量
const pageCurrent = ref<number>(1);
const pageSize = ref<number>(10);
// computed
rowSelection = computed(() => {
  return tagBaseTables.value.selectedRowKeys;
});
//methods
const addRecord = async () => {
  //新加内容类型模态框条件修改
  //添加内容类型数据
  isVisible.value = true;
  isAddOrEdit.value = true;
  modAlProps.title = "新建内容类型";
  formState.contentType.value = "";
  formState.contentType.rule.id = "";
  formState.contentIcon.value = "";
  formState.logoId = "";
  uploadList.value = [];
  buttons.value = [
    {
      text: "保存",
      "html-type": "submit",
      keepAlive: true,
    },
    {
      text: "保存并继续新建",
      "html-type": "submit",
      keepAlive: true,
    },
  ];
};

const eidtRecord = async (item: dataSourceType) => {
  if (!btnPerm.value.includes('editAble')) return
  //编辑内容类型数据
  console.log(item, "item");

  isAddOrEdit.value = true;
  modAlProps.title = "编辑内容类型";
  formState.id = item.id;
  formState.contentType.rule.id = item.id;
  isVisible.value = true;
  nextTick(() => {
    uploadList.value = [];
    if (item.id && item.logoUrl) {
      uploadList.value.push({ id: item.id, url: item.logoUrl });
    }

  });
  const data = await request.fetchContentTypeDetail({ id: item.id });
  formState.logoId = data.logoId;
  formState.contentType.value = data.typeName;
  formState.contentIcon.value = data.logoUrl;

  buttons.value = [
    {
      text: "保存",
      "html-type": "submit",
      keepAlive: true,
    },
  ];
};

const buttonMessage = async (msg: dataSourceType) => {
  // 新添或编辑内容类型调取接口
  //保存
  contentTypeFrom.value
    .validate()
    .then(() => {
      let params: dataSourceType = {
        typeName: formState.contentType.value,
        logoId: formState.logoId,
        id: formState.id,
      };
      let type: string = modAlProps.title.includes("编辑") ? "Edit" : "Add";

      request[type === "Edit" ? "fetchContentTypeUpdate" : "fetchContentTypeAdd"](params)
        .then((res: any) => {
          if (res.code == "00000 00000") {
            getRdecord();
            message.success(res.message);
          } else {
            message.error(res.message);
          }
        })
        .catch((err: any) => {
          throw new Error(err);
        });

      isVisible.value = msg.text == "保存" ? false : true;
      uploadList.value = [];
      formState.contentType.value = "";
    })
    .catch(() => { });
};

const confirmDelete = async (item: any) => {
  // 删除单个内容类型
  deleteArr.value = [item.id];
  deleteRecords(deleteArr.value);
};

const deleteSelectedAll = async () => {
  //删除已选所有内容类型
  let keys: (string | number)[] = rowSelection.value;
  Modal.confirm(
    Object.assign({}, msgModal.confirm, {
      title: "您确定删除选中的内容类型？删除后无法恢复",
      content: "删除内容类型后，内容处也同时删除",
      icon: createVNode("i", {
        class: "iconfont icon-warn warning_ICON",

      }),
      okText: "确定",
      onOk: async () => {
        await deleteRecords(keys);
        Modal.destroyAll();
      },
      onCancel() {
        Modal.destroyAll();
      },
    })
  );
};
const deleteRecords = async (keys: (string | number)[] = []) => {
  // 调接口删除内容类型
  await request.fetchContentTypeDeleteList({ idList: keys }).then((res: any) => {
    if (res.code == "00000 00000") {
      message.success(res.message);
      getRdecord();
    } else {
      message.error(res.message);
    }
  });
};
const onSearch = async () => {
  //搜索获取数据参数配置
  datas.name = name.value;
  getRdecord();
};
const getRdecord = async () => {
  // 获取表格数据
  const data: {} = {
    pageNumber: datas.pageNumber || pageCurrent.value,
    pageSize: datas.pageSize || pageSize.value,
    typeName: datas.name || "",
  };
  const contentData = (await request.fetchContentTypePageList(data)) || {};
  let reqData = contentData;
  let sourceData = ref<dataSourceType[]>([]);
  const records: any[] = [];
  reqData?.records?.map((item: any, index: number) => {
    sourceData = {
      ...item.middleDto,
      logoUrl: item.logoUrl,
      oparation: ["编辑", "删除"],
      createTime: item.createTime,
      typeName: item.typeName,
      createUser: item.createUser,
      logoId: item.logoId,
      id: item.id,
    };
    records.push(sourceData);
  });
  configData.total = reqData.total;
  configData.size = reqData.size;
  configData.records = records;
  tagBaseTables.value.selectedRowKeys = [];
  nextTick(() => {
    scroll.y = getTableScroll(74, "contentType").y;
    scroll.isFixed = getTableScroll(74, "contentType").isFixed;
  });
};

// 上传图片返回值
const uploadFinished = (data: any) => {
  formState.logoId = data[0].id;
  uploadList.value = data;
};

// 删除图片
const upload_remove_Finished = (data: any) => {
  uploadList.value = [];
  formState.logoId = ''
};
// 点击查看图片大图
const seeBigPic = (src: any) => {
  recordSrc.value = src;
  getImageStyle(src);
  nextTick(() => {
    previewVisible.value = true;
  });
};
const getImageStyle = (src: string) => {
  const url = src;
  if (url) {
    var img = new Image();
    img.src = url;
    img.onload = function () {
      if (img.naturalWidth >= img.naturalHeight) {
        styles.value = `width:100%;height:auto`;
      } else {
        styles.value = `width:auto;height:100%`;
      }
    };
  }
};
//切换分页器
const changePage = (data: { pageCurrent: any; pageSize: any }) => {
  datas = {
    pageNumber: data.pageCurrent,
    pageSize: data.pageSize,
  };
  pageCurrent.value = data.pageCurrent;
  pageSize.value = data.pageSize;
  getRdecord();
};

//onmounted
onMounted(() => {
  btnPerm.value = routerPerm()
  getRdecord();
});
</script>
<style lang="scss" scoped>
.contentType {
  width: 100%;
  height: calc(100% - 72px);
  padding: 16px;
  background-color: #fff;
  overflow: hidden;

  .contentType_button {
    padding-bottom: 16px;
    display: flex;

    .addButton {
      display: flex;
      align-items: center;
      margin-right: 8px;

      .iconadd {
        font-size: 24px;
        margin-right: 4px;
      }
    }

    .importButton {
      font-weight: 400;
      color: rgba(0, 0, 0, 0.85);
      margin-right: 8px;
    }

    .searchContent {
      margin-left: auto;
      margin-right: 0px;

      .icon-search {
        font-size: 20px;
        color: rgba(0, 0, 0, 0.45);
        position: absolute;
        right: 12px;
        top: 0px;
      }
    }
  }

  :deep(.ant-table-thead .ant-table-cell:nth-last-of-type(1)) {
    text-align: right;
    margin-right: 16px;
  }

  .eidtRecords {
    margin-right: 16px;
  }
}

:deep(.ant-form-item:nth-last-of-type(1)) {
  margin-left: 0px;
}

::v-deep(.ant-input-affix-wrapper) {
  width: 480px;
  margin-left: 4px;
}

::v-deep(.ant-form-item-control-input-content:hover) {
  .anticon-close-circle {
    display: block;
  }

  .ant-input-show-count-suffix {
    // display: none;
  }
}

::v-deep(.ant-form-item-label) {
  width: 108px;
}

::v-deep(.ant-upload.ant-upload-select-picture-card) {
  margin-left: 4px;
}

::v-deep(.anticon-close-circle) {
  display: none;
}
</style>
<style lang="scss">
.contentType {
  .ant-table-cell {
    position: relative;

    .pic {
      max-width: 24px;
      max-height: 24px;
      position: absolute;
      top: 0;
      bottom: 0;
      left: 16px;
      width: 100%;
      margin: auto;
    }
  }
}
</style>
